package com.example.springboot.controller;

import com.example.springboot.common.Constants;
import com.example.springboot.common.Page;
import com.example.springboot.entity.User;
import org.springframework.web.bind.annotation.*;
import com.example.springboot.common.Result;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.example.springboot.service.IRoleService;
import com.example.springboot.entity.Role;

import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/role")
    public class RoleController {
    
    @Resource
    private IRoleService roleService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Role role) {
        return Result.success(roleService.saveOrUpdate(role));
    }

    //根据id删除
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(roleService.removeById(id));
    }

    //根据id批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(roleService.removeByIds(ids));
    }

    //查找所有
    @GetMapping
    public Result findAll() {
        return Result.success(roleService.list());
    }

    //根据id查找
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(roleService.getById(id));
    }

    //根据名称分页查询
    @GetMapping("/findPageByRolename")
    public Result findPageByUsername(@RequestParam(defaultValue = "1") int PageNum,
                                     @RequestParam(defaultValue = "5") int PageSize,
                                     @RequestParam(defaultValue = "") String name) {
        Page page = new Page();
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name",name);
        List<Role> list = roleService.list(queryWrapper);
        if(list.isEmpty()) {
            return Result.error(Constants.CODE_600,null);
        }
        return Result.success(page.startPage(list,PageNum,PageSize));
    }

    //绑定角色和菜单的关系
    @PostMapping("/roleMenu")
    public Result roleMenu(@RequestBody Map<String,Object> roleMenuId) {
        Integer rId = Integer.parseInt(roleMenuId.get("roleId").toString());
        List<Integer> mId = roleService.objToList(roleMenuId.get("menuIds"));
        roleService.setRoleMenu(rId , mId);
        return Result.success();
    }

    @GetMapping("/getRoleMenu/{roleId}")
    public Result getRoleMenu(@PathVariable Integer roleId){
        List<Integer> menuIds = roleService.getRoleMenu(roleId);
        return Result.success(menuIds);
    }
}

